package Action.user;

import Action.Sys.Setting;
import Bean.BookCommentEntity;
import Bean.BookInfoEntity;
import Bean.LoanBookLogRecord;
import Bean.Log.HistoricalData;
import Bean.Log.OrderLog;
import Bean.UserinfoEntity;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import org.hibernate.Session;
import tools.HibernateTools;

import java.util.List;

public class LoanBook  extends ActionSupport {
    int user_key;
    int book_key;
    int day;

    BookInfoEntity bookInfoEntity;
    UserinfoEntity userinfoEntity;
    String err;
    List<BookCommentEntity> bookCommentEntities;
    List<BookInfoEntity> relateBooks;
    String commentsize;
    Session session;
    public String build_orders(){
        user_key= (int)ActionContext.getContext().getSession().get("userid");
        clearErrorsAndMessages();
        session = HibernateTools.getSession();
        userinfoEntity = session.get(UserinfoEntity.class, user_key);
        initBookInfo();

        //借书逻辑
        if (day==0){
            addActionError("请输入借书天数");
            return ERROR;
        }
        if (bookInfoEntity.getSum()<=bookInfoEntity.getUsed())
        {
            err="图书剩余不足，无法创建订单";
            addActionError(err);
            return ERROR;
        }
        if (check_user())
        {
            err="当前用户没有权限预约书籍，请联系管理员";
            addActionError(err);
            return ERROR;
        }
        session=HibernateTools.getSession();//图书信息初始化过程中防止出现session的关闭
        List<LoanBookLogRecord> data=session.createQuery("from LoanBookLogRecord  where userId=?  and (state=? or state=? " +
                "or state=?)  order by id desc ")
                .setParameter(0, user_key)
                .setParameter(1, Setting.LoanBook_state_need_Return)
                .setParameter(2, Setting.LoanBook_state_reservation)
                .setParameter(3, Setting.LoanBook_state_need_TimeOut)
                .getResultList();
        for (LoanBookLogRecord datum : data) {
            if (datum.getBookId()==book_key)
            {
                err="每人限制订阅一本同样的书";
                addActionError(err);
                return ERROR;
            }
        }
        if (data.size()>=Setting.LoanBook_Max_Num)
        {
            err="未还书籍超过最大数量,不能借书";
            addActionError(err);
            return ERROR;
        }

        //虽然此处前台有限制,但是以防万一吧
        if (day>Setting.LoanBook_Max_day||day<Setting.LoanBook_Min_day){
            err="借阅时间不合法,最多为"+Setting.LoanBook_Max_day+"天,最少是"+Setting.LoanBook_Min_day+"天";
            addActionError(err);
            return ERROR;
        }
        //正确逻辑:
        LoanBookLogRecord loanBookLogRecord=new LoanBookLogRecord();
//        loanBookLogRecord.setLoanTime();//已经由构造函数自动完成
        loanBookLogRecord.setBookId(book_key);
        loanBookLogRecord.setUserId(user_key);
        loanBookLogRecord.setDay(day);
        loanBookLogRecord.setState(Setting.LoanBook_state_reservation);
        session.save(loanBookLogRecord);
        bookInfoEntity.setUsed(bookInfoEntity.getUsed()+1);
        session.update(bookInfoEntity);

        HistoricalData historicalData=session.get(HistoricalData.class, tools.TimeTools.formatTime(0));
        if (historicalData==null){
            historicalData=new HistoricalData();
            historicalData.setTimestamp(tools.TimeTools.formatTime(0));
        }
        historicalData.setOrderNum(historicalData.getOrderNum()+1);
        session.saveOrUpdate(historicalData);


        OrderLog.addLog(loanBookLogRecord.getId(), "预约");
        addActionMessage("预约成功,请到我的订单查看");
        HibernateTools.commit(session);
        return SUCCESS;
    }

    private void initBookInfo() {

        bookInfoEntity = session.load(BookInfoEntity.class, book_key);//懒加载
        bookCommentEntities=session.createQuery("from BookCommentEntity where bookId=? order by id desc ").setParameter(0, bookInfoEntity.getId()).setMaxResults(1000).getResultList();
        commentsize=""+(bookCommentEntities.size()==1000?"999+":bookCommentEntities.size());
        try {
            bookInfoEntity.build_image(false);
        } catch (Exception e){
            System.err.println("图片生成失败");
        }

        //相关书籍算法:-----
        relateBooks=bookInfoEntity.related_books(5);
        for (BookInfoEntity relateBook : relateBooks) {
            try {
                relateBook.build_image(false);
            } catch (Exception e) {
                System.err.println("图片生成失败");
            }
        }
    }

    private boolean check_user() {
        return false;
    }

    public int getBook_key() {
        return book_key;
    }

    public void setBook_key(int book_key) {
        this.book_key = book_key;
    }

    public BookInfoEntity getBookInfoEntity() {
        return bookInfoEntity;
    }

    public void setBookInfoEntity(BookInfoEntity bookInfoEntity) {
        this.bookInfoEntity = bookInfoEntity;
    }

    public UserinfoEntity getUserinfoEntity() {
        return userinfoEntity;
    }

    public void setUserinfoEntity(UserinfoEntity userinfoEntity) {
        this.userinfoEntity = userinfoEntity;
    }

    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }

    public String getErr() {
        return err;
    }

    public void setErr(String err) {
        this.err = err;
    }

    public List<BookCommentEntity> getBookCommentEntities() {
        return bookCommentEntities;
    }

    public void setBookCommentEntities(List<BookCommentEntity> bookCommentEntities) {
        this.bookCommentEntities = bookCommentEntities;
    }

    public List<BookInfoEntity> getRelateBooks() {
        return relateBooks;
    }

    public void setRelateBooks(List<BookInfoEntity> relateBooks) {
        this.relateBooks = relateBooks;
    }

    public String getCommentsize() {
        return commentsize;
    }

    public void setCommentsize(String commentsize) {
        this.commentsize = commentsize;
    }
}
